package com.fitns.user.service.baseConfig;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.fitns.user.conf.ExcelConstants;
import com.fitns.user.dao.baseConfig.AreaPersonDao;
import com.fitns.user.dao.baseConfig.AreaVehicleDao;
import com.fitns.user.dao.baseConfig.WorkPositionDao;
import com.fitns.user.dto.baseConfig.AreaPersonVO;
import com.fitns.user.dto.baseConfig.AreaVehicleVO;
import com.fitns.user.dto.baseConfig.WorkPositionDTO;
import com.fitns.user.dto.baseConfig.WorkPositionVO;
import com.fitns.user.exception.ServiceException;
import com.fitns.user.exception.WorkPositionMsgCode;
import com.fitns.user.model.baseConfig.TbAreaPerson;
import com.fitns.user.model.baseConfig.TbAreaVehicle;
import com.fitns.user.model.baseConfig.TbWorkPosition;
import com.fitns.user.utils.RandomCodeUtils;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.lang.Validator;

import tk.mybatis.mapper.util.StringUtil;


@Service
public class WorkPositionService {

	@Autowired
	private WorkPositionDao workPositionDao;

    @Autowired
    private AreaPersonDao areaPersonDao;

    @Autowired
    private AreaVehicleDao areaVehicleDao;

    /**
     * 新增
     * @param workPositionDTO
     * @return
     */
	public WorkPositionVO insert(WorkPositionDTO workPositionDTO){
		if(Validator.isNull(workPositionDTO)){
			throw ServiceException.create(WorkPositionMsgCode.WORK_POSITION_ORGAN_OR_IS_NULL);

		}
		//随机生成区域编号
		String areaCode = RandomCodeUtils.getRandomCode(9);
        workPositionDTO.setAreaNum("AR"+areaCode);
		String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		Timestamp createDate=Timestamp.valueOf(nowDate);
        workPositionDTO.setCreateTime(createDate);
        workPositionDTO.setModifyTime(createDate);
        TbWorkPosition tbWorkPosition = new TbWorkPosition();
        BeanUtils.copyProperties(workPositionDTO, tbWorkPosition);
		workPositionDao.insert(tbWorkPosition);
        WorkPositionVO workPositionVO = new WorkPositionVO();
		BeanUtils.copyProperties(tbWorkPosition, workPositionVO);
		//工作人员关联新增
        List<TbAreaPerson> areaPersonList = new ArrayList<>();
        if(Validator.isNotNull(workPositionDTO.getAreaPersonVOList())) {
            for (AreaPersonVO areaPersonVO : workPositionDTO.getAreaPersonVOList()) {
                TbAreaPerson areaPerson = new TbAreaPerson();
                areaPerson.setAreaId(tbWorkPosition.getId());
                areaPerson.setPersonId(areaPersonVO.getPersonId());
                //直接进行新增
                areaPersonDao.insert(areaPerson);
                areaPersonList.add(areaPerson);
            }
        }
        workPositionVO.setAreaPersonVOList(workPositionDTO.getAreaPersonVOList());
        //工作车辆关联新增
        List<TbAreaVehicle> areaVehicleList = new ArrayList<>();
        if(Validator.isNotNull(workPositionDTO.getAreaVehicleVOList())) {
            for (AreaVehicleVO areaVehicleVO : workPositionDTO.getAreaVehicleVOList()) {
                TbAreaVehicle areaVehicle = new TbAreaVehicle();
                areaVehicle.setAreaId(tbWorkPosition.getId());
                areaVehicle.setVehicleId(areaVehicleVO.getVehicleId());
                //直接进行新增
                areaVehicleDao.insert(areaVehicle);
                areaVehicleList.add(areaVehicle);
            }
        }
        workPositionVO.setAreaVehicleVOList(workPositionDTO.getAreaVehicleVOList());
		return workPositionVO;
	}

    /**
     * 修改
     * @param workPositionDTO
     * @return
     */
    public WorkPositionVO modify(WorkPositionDTO workPositionDTO){
        if(Validator.isNull(workPositionDTO)){
            throw ServiceException.create(WorkPositionMsgCode.WORK_POSITION_ORGAN_OR_IS_NULL);
        }
        TbWorkPosition workPosition = workPositionDao.selectByPrimaryKey(workPositionDTO.getId());
        if(Validator.isNull(workPositionDTO)) {
            throw ServiceException.create(WorkPositionMsgCode.WORK_POSITION_DATA_IS_NULL);
        }
        String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Timestamp modifyDate=Timestamp.valueOf(nowDate);
        workPositionDTO.setModifyTime(modifyDate);
        TbWorkPosition tbWorkPosition = new TbWorkPosition();
        BeanUtils.copyProperties(workPositionDTO, tbWorkPosition);
        workPositionDao.modify(tbWorkPosition);
        WorkPositionVO workPositionVO = new WorkPositionVO();
        BeanUtils.copyProperties(tbWorkPosition, workPositionVO);
        //删除原来的工作人员和工作车辆
        areaPersonDao.delete(tbWorkPosition.getId());
        areaVehicleDao.delete(tbWorkPosition.getId());
        //工作人员关联新增
        List<TbAreaPerson> areaPersonList = new ArrayList<>();
        if(Validator.isNotNull(workPositionDTO.getAreaPersonVOList())) {
            for (AreaPersonVO areaPersonVO : workPositionDTO.getAreaPersonVOList()) {
                TbAreaPerson areaPerson = new TbAreaPerson();
                areaPerson.setAreaId(tbWorkPosition.getId());
                areaPerson.setPersonId(areaPersonVO.getPersonId());
                //直接进行新增
                areaPersonDao.insert(areaPerson);
                areaPersonList.add(areaPerson);
            }
        }
        workPositionVO.setAreaPersonVOList(workPositionDTO.getAreaPersonVOList());
        //工作车辆关联新增
        List<TbAreaVehicle> areaVehicleList = new ArrayList<>();
        if(Validator.isNotNull(workPositionDTO.getAreaVehicleVOList())) {
            for (AreaVehicleVO areaVehicleVO : workPositionDTO.getAreaVehicleVOList()) {
                TbAreaVehicle areaVehicle = new TbAreaVehicle();
                areaVehicle.setAreaId(tbWorkPosition.getId());
                areaVehicle.setVehicleId(areaVehicleVO.getVehicleId());
                //直接进行新增
                areaVehicleDao.insert(areaVehicle);
                areaVehicleList.add(areaVehicle);
            }
        }
        workPositionVO.setAreaVehicleVOList(workPositionDTO.getAreaVehicleVOList());
        return workPositionVO;
    }

    /**
     * 查询列表
     * @param tbWorkPosition
     * @return
     */
    public PageInfo<WorkPositionVO> select(TbWorkPosition tbWorkPosition) {
        if(StringUtils.isEmpty(tbWorkPosition)){
            return null;
        }
        List<WorkPositionVO> workPositionVOList = workPositionDao.selectList(tbWorkPosition);
        for(WorkPositionVO workPositionVO : workPositionVOList){
            TbAreaPerson tbAreaPerson = new TbAreaPerson();
            TbAreaVehicle tbAreaVehicle = new TbAreaVehicle();
            tbAreaPerson.setAreaId(workPositionVO.getId());
            tbAreaVehicle.setAreaId(workPositionVO.getId());
            workPositionVO.setAreaPersonVOList(areaPersonDao.selectList(tbAreaPerson));
            workPositionVO.setAreaVehicleVOList(areaVehicleDao.selectList(tbAreaVehicle));
        }
        PageInfo<WorkPositionVO> pageInfo=new PageInfo<>(workPositionVOList);
        return pageInfo;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional
    public long delete(Long id){
        if(Validator.isNull(id)){
            throw ServiceException.create(WorkPositionMsgCode.WORK_POSITION_ID_IS_NULL);
        }
        TbWorkPosition tbWorkPosition=workPositionDao.selectByPrimaryKey(id);
        if(Validator.isNull(tbWorkPosition)){
            throw ServiceException.create(WorkPositionMsgCode.WORK_POSITION_DATA_IS_NOT_EXIST);
        }
        areaPersonDao.delete(id);
        areaVehicleDao.delete(id);
        workPositionDao.deleteByPrimaryKey(id);
        return id;
    }

    /**
     * excel导入
     * @param excelList
     * @param organId
     * @param type
     * @return
     */
    public List<WorkPositionDTO> importExcel(List<List<String>> excelList, long organId, String type){
        List<WorkPositionDTO> dtoList=new ArrayList<>();
        List<WorkPositionDTO> msgList=new ArrayList<>();

        for (int i = 1; i <excelList.size() ; i++) {
            String number=excelList.get(i).get(0);
            if(!StringUtils.isEmpty(number)){
                WorkPositionDTO workPositionDTO=this.validateExcel(excelList.get(i),i);
                if(!StringUtils.isEmpty(workPositionDTO.getMsg())){
                    msgList.add(workPositionDTO);
                }else {
                    WorkPositionDTO dataVo=this.importDetail(excelList.get(i));
                    dtoList.add(dataVo);
                }
            }
        }
        if(Validator.isEmpty(msgList)||msgList.size()==0){
            if(Validator.isNotEmpty(dtoList)&&dtoList.size()!=0){
                dtoList.forEach(workPositionDTO -> {
                    TbWorkPosition tbWorkPosition=new TbWorkPosition();
                    BeanUtils.copyProperties(workPositionDTO,tbWorkPosition);
                    tbWorkPosition.setType(type);
                    tbWorkPosition.setOrganId(organId);
                    //随机生成区域编号
                    String randomCode = RandomCodeUtils.getRandomCode(6);
                    tbWorkPosition.setAreaNum("AR"+randomCode);
                    String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    Timestamp createDate=Timestamp.valueOf(nowDate);
                    tbWorkPosition.setCreateTime(createDate);
                    tbWorkPosition.setModifyTime(createDate);
                    workPositionDao.insert(tbWorkPosition);
                    //新增人员和车辆
                    String phones = workPositionDTO.getPhones();
                    String cards = workPositionDTO.getCards();
                    if(!StringUtils.isEmpty(phones)) {
                        String[] phonesArr = phones.split(";");
                        for (String phone : phonesArr) {
                            //通过phone查询人员台账表的id，然后添加数据至区域与人员中间表
                            //Long personId = personLedgerDao.selectIdByPhone(phone);
                            TbAreaPerson areaPerson = new TbAreaPerson();
                            areaPerson.setAreaId(tbWorkPosition.getId());
                           // areaPerson.setPersonId(personId);
                            //直接进行新增
                           // areaPersonDao.insert(areaPerson);
                        }
                    }
                    if(!StringUtils.isEmpty(cards)) {
                        String[] cardsArr = cards.split(";");
                        for (String card : cardsArr) {
                            //通过card查询车辆台账表的id，然后添加数据至区域与车辆中间表
                            //Long vehicleId = vehicleLedgerDao.selectIdByCard(card);
                            TbAreaVehicle areaVehicle = new TbAreaVehicle();
                            areaVehicle.setAreaId(tbWorkPosition.getId());
                           // areaVehicle.setVehicleId(vehicleId);
                            //直接进行新增
                           // areaVehicleDao.insert(areaVehicle);
                        }
                    }
                });
            }else {
                WorkPositionDTO workPositionDTO=new WorkPositionDTO();
                workPositionDTO.setMsg(ExcelConstants.WORK_POSITION_IMPORT.EXCEL_IS_NULL);
                msgList.add(workPositionDTO);
            }
        }
        return msgList;
    }

    /**
     * 转储数据
     * @param excelList
     * @return
     */
    public WorkPositionDTO importDetail(List<String> excelList){
        WorkPositionDTO workPositionDTO=new WorkPositionDTO();
        workPositionDTO.setName(excelList.get(1));
        workPositionDTO.setPhones(excelList.get(2));
        workPositionDTO.setCards(excelList.get(3));
        if(StringUtil.isNotEmpty(excelList.get(4))) {
            workPositionDTO.setAcreage(Float.parseFloat(excelList.get(4)));
        }
        workPositionDTO.setDescs(excelList.get(5));
        workPositionDTO.setPosition(excelList.get(6));
        return workPositionDTO;
    }

    /**
     * 验证表格
     * @param excelList
     * @param i
     * @return
     */
    public WorkPositionDTO validateExcel(List<String> excelList, int i){
        WorkPositionDTO workPositionDTO=new WorkPositionDTO();
        StringBuilder msg = new StringBuilder();
        if(StringUtils.isEmpty(excelList.get(1))) {
            msg.append("第" + (i + 1) + "行" + ExcelConstants.WORK_POSITION_IMPORT.WORK_POSITION_NAME_IS_NULL);
        }

        if(!StringUtils.isEmpty(msg)){
            workPositionDTO.setMsg(msg.toString());
        }
        return workPositionDTO;
    }

}
